<template>
  <a-card :bordered="false" class="warp" ref="warp">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24" >
            <a-form-item label="年份">
              <j-dict-select-tag :value="year" :triggerChange="true" @change="yearChange" placeholder="请选择数据类型" dict-code="year_value"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button  type="primary" icon="search" @click="searchQuery">查询</a-button>
              <a-button type="primary" icon="reload" style="margin-left: 8px" @click="searchReset">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-spin :spinning="spinning" size="large" >
      <bar-multid :dataSource="saleProject" v-if="saleProject.length>0" :fields="fields" title="Top10项目月成交概率变动" xField="project"></bar-multid>
      <div v-if="saleProject.length === 0 && clientDatas.length>0">
        <h4>Top10项目月成交概率变动</h4>
        <a-empty />
      </div>
      <div v-if="clientDatas.length>0">
        <a-row>
          <a-col :span="12"><h4 >{{`Top${range}客户接触与概率变动对比`}}</h4></a-col>
          <a-col :span="12" style="text-align: right;">
            <!-- <a-radio-group :value="isMonthView" @change="callback">
              <a-radio-button value="1">
                月
              </a-radio-button>
              <a-radio-button value="2">
                周
              </a-radio-button>
            </a-radio-group> -->
          </a-col>
        </a-row>
        <template v-for="(item,i) in clientDatas">
          <bar-and-line :key="i" v-if="i<range" :height="170" :dataSource="datas[i]" yField="true" :axisTitlt="item.project"></bar-and-line>
        </template>
        <a-slider class="chart-range" :min="1" :max="12" v-model="range" v-if="isShowRange" />
        <a-button shape="circle" icon="plus" class="button-chart-range" type="primary" ghost v-if="isMonthView !== '1'" @click="() => this.isShowRange = !this.isShowRange" />
        <v-plugin class="chart-slider" v-if="clientDatas.length>0 && isMonthView !== '1' && isShowSilder">
          <v-slider width="auto" :height="26"
            container='viser-slider-1'
            :start="start" :end="end"
            :data="clientDatas[0].data" xAxis="month" yAxis="dealProbability" :on-change="slideChange" />
        </v-plugin>
        <a-button shape="circle" icon="setting" class="button-chart-set" type="primary" ghost v-if="isMonthView !== '1'" @click="chartShowSlider" />

      </div>
      <a-empty v-else />
    </a-spin>
  </a-card>
</template>

<script>
import { DataSet } from '@antv/data-set'
import { postAction } from '@/api/manage'
import BarAndLine from './modules/BarAndLine'
import BarMultid from '@/components/chart/BarMultid'

const title = {
  offset: 50
}
export default {
  name: 'SaleChangingTrend',
  components: {
    BarAndLine,
    BarMultid
  },
  data() {
    return {
      adjust: [{
        type: 'dodge',
        marginRatio: 1 / 32
      }],
      title,
      width: 0,
      padding: { top: 10, right: 50, bottom: 80, left: 80 },
      color: ['line', ['#67b7dc', '#84b761', '#fdd400', '#cc4748', '#cd82ad', '#2f4074', '#448e4d', '#b7b83f', '#b9783f']],
      clientDatas: [],
      url: {
        list: '/sale/statisticalReports/getTop10ProjectTransactionProbabilityChangesData',
        getSaleProjectByMap: '/sale/statisticalReports/getSaleProjectByMap'
      },
      spinning: false,
      datas: [],
      start: '第1周',
      end: '第12周',
      year: '',
      isMonthView: '2',
      setTimeout_: '',
      isShowSilder: false,
      saleProject: [],
      fields: [],
      isShowRange: false,
      range: 5
    }
  },
  mounted() {
    this.year = new Date().getFullYear()
    this.setRange()
    this.loadData()
    setTimeout(() => { // 解决图表渲染时超宽
      this.width = this.$refs.warp.$el.offsetWidth - 48
    }, 500)
  },
  methods: {
    searchQuery() {
      this.loadData()
    },
    searchReset() {
      this.year = new Date().getFullYear()
      this.loadData()
    },
    yearChange(value) {
      this.year = value
    },
    callback(e) {
      this.isMonthView = e.target.value
      setTimeout(() => { // 解决tab切换卡顿
        this.loadProjectTransactionData()
      }, 60)
    },
    slideChange(opts) {
      this.start = opts.startText
      this.end = opts.endText
      if (this.setTimeout_) {
        clearTimeout(this.setTimeout_)
      }
      this.setTimeout_ = setTimeout(() => {
        this.chartData()
      }, 1000)
    },
    chartShowSlider() {
      this.isShowSilder = !this.isShowSilder
    },
    loadProjectTransactionData() {
      let isOnly
      if (!this.spinning) {
        this.spinning = true// 单独请求时 弹出加载提示
        isOnly = true
      }
      this.spinning = true
      return postAction(this.url.list, { 'year': this.year, isMonthView: this.isMonthView }).then(res => {
        if (res.success) {
          this.clientDatas = res.result
          this.chartData()
        }
        isOnly ? this.spinning = false : ''
      })
    },
    loadSaleProjectData() {
      return postAction(this.url.getSaleProjectByMap, { 'year': this.year }).then(res => {
        if (res.success) {
          this.saleProject = res.result
          if (this.saleProject[0]) {
            this.fields = Object.keys(this.saleProject[0])
            const index = this.fields.indexOf('project')
            this.fields.splice(index, 1)
          }
        }
      })
    },
    loadData() {
      this.spinning = true
      Promise.all([
        this.loadProjectTransactionData(),
        this.loadSaleProjectData()
      ]).then(arr => {
        this.spinning = false
      })
    },
    getData(data) { // 单独组装组合图表的数据
      const ds = new DataSet({
        state: {
          start: this.start,
          end: this.end
        }
      })
      const dv = ds.createView().source(data)
      if (this.isMonthView === '2') {
        // const starti = this.start.replace('周', '') * 1
        // const endi = this.end.replace('周', '') * 1
        const starti = this.start.replace(/[^0-9]/ig, '') * 1
        const endi = this.end.replace(/[^0-9]/ig, '') * 1
        dv.transform({
          type: 'filter',
          callback: obj => {
            const i = obj.month.replace(/[^0-9]/ig, '') * 1
            return starti <= i && i <= endi
          }
        })
      }
      dv.transform({
        type: 'fold',
        fields: ['dealProbability'],
        key: 'line',
        value: 'lineValue'
      }).transform({
        type: 'fold',
        fields: ['effectiveNumber', 'actualNumber'],
        key: 'bar',
        value: 'barValue'
      })
      const rows = dv.rows
      rows.forEach(row => { // 替换别名
        if (row.line === 'dealProbability') {
          row.line = '成交概率'
        }
        if (row.bar === 'effectiveNumber') {
          row.bar = '有效接触次数'
        }
        if (row.bar === 'actualNumber') {
          row.bar = '实际接触次数'
        }
      })
      return dv.rows
    },
    chartData() {
      const datas = []
      this.clientDatas.forEach((item, i) => {
        datas.push(this.getData(item.data))
      })
      this.datas = datas
    },
    getWeek(dt) {
      const d1 = new Date(dt)
      const d2 = new Date(dt)
      d2.setMonth(0)
      d2.setDate(1)
      const rq = d1 - d2
      const days = Math.ceil(rq / (24 * 60 * 60 * 1000))
      const num = Math.ceil(days / 7)
      return num + 1
    },
    setRange() {
      const date_ = new Date()
      if (this.year === date_.getFullYear()) {
        const week = this.getWeek(date_.getFullYear() + '-' + (date_.getMonth() + 1) + '-' + date_.getDate())
        if (week <= 12) {
          this.start = '第1周'
          this.end = '第12周'
        } else {
          this.start = '第' + week - 12 + '周'
          this.end = '第' + week + '周'
        }
      } else {
        this.start = '第1周'
        this.end = '第12周'
      }
    }
  }
}
</script>
<style scoped>
  .button-chart-set{
    position: fixed;
    bottom: 50px;
    right: 100px;
  }
  .chart-slider{
    position: fixed;
    bottom: 50px;
    right: 130px;
    width: 500px;
  }
  .button-chart-range{
    position: fixed;
    bottom: 100px;
    right: 100px;
  }
  .chart-range{
    position: fixed;
    bottom: 100px;
    right: 140px;
    width: 200px;
  }
</style>
